package com.pilihou.utils
{
	import com.pilihou.events.MultiOpenImageEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.geom.Matrix;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	public class MultiOpenImage extends EventDispatcher
	{
		private var _imageType:FileFilter=new FileFilter("图像格式(*.jpg,*.jpeg,*.gif,*.png)", "*.jpg;*.jpeg;*.gif;*.png;");
		private var _fileRefList:FileReferenceList;
		private var _file:FileReference;
		private var _files:ArrayCollection;
		private var _maxFileSize:Number=2*1024*1024;//文件最大字节
		private var _maxNum:Number=800;//文件最大宽高
		private var _max:Number=9;//打开图片的最多文件数
		private var _byteArr:Array=[];//打开文件数据数组
		private var bmpArr:Array=[];
		private var loader:Loader;
		public function MultiOpenImage(target:IEventDispatcher=null)
		{
			super(target);
			_fileRefList=new FileReferenceList();
			_fileRefList.addEventListener(Event.SELECT,fileRefList_selectHandler);
			_file=new FileReference();
			_files = new ArrayCollection();
			
		}
		
		public function browseFiles():void{        
			//浏览文件
			_fileRefList.browse([_imageType]);
			bmpArr=[];
			
		}
		
		//在用户从浏览对话框选择文件后调用。
		private function fileRefList_selectHandler(event:Event):void
		{
			var i:int;
			var msg:String ="";
			var exceedArr:Array = [];                          
			for (i=0;i < event.currentTarget.fileList.length; i ++)
			{
				if (checkFileSize(event.currentTarget.fileList[i].size))
				{
					_files.addItem(event.currentTarget.fileList[i]);
				}
				else
				{
					exceedArr.push(event.currentTarget.fileList[i]);
				}
			}                
			if (exceedArr.length > 0){
				for (i=0;i<exceedArr.length;i++)
				{
					msg += String(exceedArr[i].name + " 文件太大. \n");
				}
				//trace(msg + "Max File Size is: " + Math.round(_maxFileSize / 1024) + " kb","文件太大,4,null).clipContent;
			}
			if (_files.length > 0)
			{
				uploadFiles();
			}
			
		}
		
		//检查的文件大小不超过maxFileSize，如果_maxFileSize == 0则文件没有大小限制
		private function checkFileSize(filesize:Number):Boolean{
			
			var isExceed:Boolean = false;
			//如果filesize大于 _maxFileSize
			if (filesize > _maxFileSize)
			{
				isExceed = false;
			}
			else if (filesize <= _maxFileSize)
			{
				isExceed = true;
			}
			
			if (_maxFileSize == 0)
			{
				isExceed = true;
			}
			
			return isExceed;
		}
		
		private function uploadFiles():void
		{
			_file = FileReference(_files.getItemAt(0));
			_file.addEventListener(Event.COMPLETE, completeHandler);
			_file.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			_file.load();
		}
		
		// 文件成功上传后调用 | 我们使用这个以及检查是否有上传所有文件，以及如何处理它
		private function completeHandler(event:Event):void{
			//trace('completeHanderl被触发');
			_file.removeEventListener(Event.COMPLETE, completeHandler);
			_byteArr.push(event.target.data);
			_files.removeItemAt(0);
			if (_files.length > 0)
			{
				uploadFiles();
			}
			else
			{
				if(_byteArr.length>0)
				{
					loadFiles();
				}
			}
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			_file.removeEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			_files.removeItemAt(0);
			if (_byteArr.length > 0)
			{
				uploadFiles();
			}
		}
		//加载字节数组中第一个元素
		private function loadFiles():void
		{
			loader=new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loader_completeHandler);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,loader_ioErrorHandler);
			loader.loadBytes(_byteArr[0]);
		}
		//加载字节数组完成把它转成图片，并缩放大小
		private function loader_completeHandler(event:Event):void
		{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,loader_completeHandler);
			var bmp:Bitmap=event.currentTarget.content as Bitmap;
			var bmd:BitmapData;
			
			if(bmp.width>=bmp.height)
			{
				if(bmp.width>_maxNum)
				{
					var rateW:Number=_maxNum/bmp.width;
					var h:Number=rateW*bmp.height;
					bmd=new BitmapData(_maxNum,h,true,0);
					bmd.draw(bmp.bitmapData,new Matrix(rateW,0,0,rateW),null,null,null,true);
				}
				else
				{
					bmd=new BitmapData(bmp.width,bmp.height,true,0);
					bmd=bmp.bitmapData.clone();
				}
				
			}
			else if(bmp.height>bmp.width)
			{
				if(bmp.height>_maxNum)
				{
					var rateH:Number=_maxNum/bmp.height;
					var w:Number=rateH*bmp.width;
					bmd=new BitmapData(w,_maxNum,true,0);
					bmd.draw(bmp.bitmapData,new Matrix(rateH,0,0,rateH),null,null,null,true);
				}
				else
				{
					bmd=new BitmapData(bmp.width,bmp.height,true,0);
					bmd=bmp.bitmapData.clone();
				}
			}
			if(bmpArr.length <_max)//限制最多文件个数
			{
				bmpArr.push(bmd.clone());
				bmd.dispose();
			}
			_byteArr.shift();//删除数组第一个元素
			if (_byteArr.length > 0)
			{
				loadFiles();
			}
			else//上传完成
			{
				var openEvent:MultiOpenImageEvent=new MultiOpenImageEvent(MultiOpenImageEvent.ALLOPEN,false,false);
				openEvent.result=bmpArr;
				dispatchEvent(openEvent);
			}
		}
		
		private function loader_ioErrorHandler(event:IOErrorEvent):void
		{
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,loader_ioErrorHandler);
			_byteArr.shift();
			if (_byteArr.length > 0)
			{
				loadFiles();
			}
		}
	}
}